package com.flyan.game.motafx.core.event;

import com.flyan.game.motafx.core.event.enums.EventListenerTypeEnum;
import com.flyan.game.motafx.core.event.listener.EventListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 事件服务
 *
 * @author flyan
 * @version 1.0
 * @email flyan_by_chenu@sina.com
 * @since 2025/2/11
 */
public class EventService {

    /**
     * 事件监听器字典
     */
    private final Map<EventListenerTypeEnum, List<EventListener>> listenerDict;

    public EventService() {
        EventListenerTypeEnum[] types = EventListenerTypeEnum.values();
        listenerDict = new HashMap<>(types.length);
        for (EventListenerTypeEnum type : types) {
            listenerDict.put(type, new ArrayList<>());
        }
    }

    /**
     * 添加事件监听器
     *
     * @param listener 监听器
     */
    public void addListener(EventListener listener) {
        EventListenerTypeEnum type = EventListenerTypeEnum.valueOfCode(listener.type());
        listenerDict.get(type).add(listener);
    }

    /**
     * 监听器类型发生
     *
     * @param type 类型
     */
    public void typeOccur(EventListenerTypeEnum type) {
        List<EventListener> listeners = listenerDict.get(type);
        List<EventListener> removed = new ArrayList<>(3);
        listeners.forEach(it -> {
            if (it.occur() && !it.isRepeated()) {
                removed.add(it);
            }
        });
        listeners.removeAll(removed);
    }

}
